﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace GFluentCode.Tools
{
    /// <summary>
    /// AppConfig文件读写
    /// </summary>
    public class AppConfigHelper
    {
        /// <summary>
        /// 读取配置项
        /// </summary>
        /// <param name="key"></param>        
        /// <returns></returns>
        public static string ReadItem(string key)
        {
            return !ConfigurationManager.AppSettings.AllKeys.Contains(key)
                ? string.Empty
                : ConfigurationManager.AppSettings[key];
        }

        /// <summary>
        /// 写配置项
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void WriteItem(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (!config.AppSettings.Settings.AllKeys.Contains(key))
            {
                //没有键值对配置，则新增
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
